﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace API.Models.Repository
{
    public class WH_ITEMS_Repository : GenericRepository<PartnerDbContext, WH_ITEMS>
    {
        public override IQueryable<WH_ITEMS> Find(System.Linq.Expressions.Expression<Func<WH_ITEMS, bool>> predicate)
        {
            IQueryable<WH_ITEMS> query = _entities.WH_ITEMS
                .Include("COMPANY");

            /// Фильтрация по заданному условию
            if (predicate != null)
                query = query.Where(predicate);

            if (session != null)
            {
                query = query
                    .Where(r => r.COMPANY_GUID == session.COMPANY_GUID);
            }

            return query.AsQueryable();
        }

        public override void Add(WH_ITEMS entity)
        {
            var record = this.Find(r =>
                    r.COMPANY_GUID == this.session.COMPANY_GUID &&
                    r.EXT_KEY == entity.EXT_KEY)
                .SingleOrDefault();

            if (record != null)
            {
                record.EXT_KEY = entity.EXT_KEY;
                record.ITEM_NAME = entity.ITEM_NAME;

                this.Edit(record);
                return;
            }

            if (entity.GUID_RECORD == null || entity.GUID_RECORD == Guid.Empty)
                entity.GUID_RECORD = Guid.NewGuid();

            entity.COMPANY_GUID = this.session.COMPANY_GUID;

            _entities.Set<WH_ITEMS>().Add(entity);
        }

        public override void Edit(WH_ITEMS entity)
        {
            entity.COMPANY_GUID = this.session.COMPANY_GUID;

            try
            {
                if (_entities.Entry(entity).State == System.Data.EntityState.Modified)
                {
                    _entities.Entry(entity).CurrentValues.SetValues(entity);
                }

                _entities.Entry(entity).State = System.Data.EntityState.Modified;
            }
            catch
            {
                /// В случае повторного обновления записи
                /// возникает ошибка
                /// нужно как-то обработать. Но как?
            }
        }
    }
}